
using B.S.RbacData.Infrastructure;
using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using NLog.Web;
using SupplierCustomerManagement.Infrastructure;
using SupplierCustomerManagement.Read.API.Automappers;
using SupplierCustomerManagement.Read.API.Data;
using System.Reflection;

namespace SupplierCustomerManagement.Read.API
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            //注册数据库上下文
            builder.Services.AddDbContext<SupplierDbContext>(options =>
            {
                options.UseMySql(builder.Configuration.GetConnectionString("mysql"), new MySqlServerVersion("5.7"));
            });
            //注册自动映射
            builder.Services.AddAutoMapper(typeof(AutomapperProfiles));
            //注册中介者模式
            builder.Services.AddMediatR(x=>x.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
            //注册仓储
            builder.Services.AddScoped(typeof(IBaseRepository<>),typeof(BaseRepository<>));
            //注册Nlog
            builder.Host.UseNLog();

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();

            builder.Services.AddSwaggerGen(o =>
            {

                //获取项目名称
                var pname=typeof(Program).Assembly.GetName().Name;

                var path =AppDomain.CurrentDomain.BaseDirectory+pname+".xml";

                o.IncludeXmlComments(path, true);
            });

            var app = builder.Build();
            //注册跨域
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                //app.UseSwaggerUI();
            }
            app.UseKnife4UI();

            app.UseAuthorization();


            app.MapControllers();

            // 开发环境：初始化测试数据（仅当库为空时）
            try
            {
                DataSeeder.SeedAsync(app.Services).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Data seeding failed: {ex.Message}");
            }

            app.Run();
        }
    }
}
